import java.util.*;

/**
 * 给定一些同学的信息（名字，成绩）序列，请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩
 * 都按先录入排列在前的规则处理。
 * 例示：
 * jack      70
 * peter     96
 * Tom       70
 * smith     67
 * 从高到低  成绩
 * peter     96
 * jack      70
 * Tom       70
 * smith     67
 * 从低到高
 * smith     67
 * jack      70
 * Tom       70
 * peter     96
 *
 * 注：0代表从高到低，1代表从低到高
 */
public class ScoreSort {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            ArrayList<Student> students = new ArrayList<>();
            int n = Integer.parseInt(scanner.nextLine());
            int sign = Integer.parseInt(scanner.nextLine());
            for (int i = 0; i < n; i++) {
                String s = scanner.nextLine();
                String[] split = s.split(" ");
                students.add(new Student(split[0],Integer.parseInt(split[1])));
            }
            Collections.sort(students, new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    if(sign == 0){
                        return o1.getScore() - o2.getScore();
                    }else {
                        return o2.getScore() - o1.getScore();
                    }
                }
            });
            for (Student student : students) {
                System.out.println(student.getName()+" "+student.getScore());
            }
        }
    }
}
class Student {
    private String name;
    private int score;

    public Student() {
    }

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

